import { reactive } from 'vue';
import { toRefs } from '@vueuse/core';
import { getDict } from '@/api/system/dict';

/**
 * 判断数据是否为Object对象
 * @param object 检测对象
 * @returns {boolean} isObject
 */
export function isObj(object) {
  return (
    object &&
    typeof object === 'object' &&
    Object.prototype.toString.call(object).toLowerCase() === '[object object]'
  );
}

/**
 * 为对象添加新的别名
 * @param obj 原有对象
 * @param filedObj
 * 新字段数据对象
 * {
 *    oldKey: newKey
 * }
 * @returns {*}
 */
export function obj2newField(obj, filedObj) {
  const newObj = { ...obj };
  if (isObj(filedObj)) {
    Object.keys(filedObj).forEach((key) => {
      if (newObj[key] !== undefined) {
        newObj[filedObj[key]] = newObj[key];
      }
    });
  }

  return newObj;
}

export function useInitDict(params, callback?: Function) {
  const map = {};
  for (const item in params) {
    map[params[item]] = [];
  }

  const reactMap = reactive(map);

  const type = Object.keys(params).join(',');
  getDict(type).then((res) => {
    if (res && res.code === 'A00000') {
      const IMap = {};
      res.data.forEach((dict) => {
        dict = obj2newField(dict, {
          dictLabel: 'label',
          dictValue: 'value',
        });
        if (!IMap[dict.dictType]) {
          IMap[dict.dictType] = [];
        }
        IMap[dict.dictType].push(dict);
      });

      for (const item in params) {
        reactMap[params[item]] = IMap[item];
      }

      if (callback) {
        callback();
      }
    }
  });

  return {
    ...toRefs(reactMap),
  };
}
